package com.yt.product.api.client;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.common.utils.StrUtils;
import com.yt.product.models.bo.SupplierInfoSaveBO;
import com.yt.product.models.dto.SupplierInfoDTO;
import com.yt.product.models.service.ISupplierInfoService;
import com.yt.product.models.vo.SupplierInfoVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/supplierInfo")
@Slf4j
@Api(value = "SupplierInfoApiController", tags = "供应商详情Api接口")
public class SupplierInfoApiController {

    @DubboReference
    private ISupplierInfoService supplierInfoService;

    @ApiOperation(value = "新增供应商", notes = "新增供应商信息")
    @PostMapping("/add")
    public Result<SupplierInfoVO> add(@RequestBody SupplierInfoSaveBO saveBO) {
        boolean success = supplierInfoService.add(saveBO);
        if (success) {
            SupplierInfoDTO dto = supplierInfoService.selectOne(
                    new EntityWrapper<SupplierInfoDTO>()
                            .eq("supplier_name", saveBO.getSupplierName())
                            .eq("phone", saveBO.getPhone())
                            .orderBy("create_time", false)
                            .last("LIMIT 1")
            );
            if (dto == null) {
                return new Result<>(CodeEnum.FAIL_100010);
            }
            SupplierInfoVO vo = new SupplierInfoVO();
            BeanUtils.copyProperties(dto, vo);
            return new Result<>(vo);
        }
        return new Result<>(CodeEnum.FAIL_100007);
    }

    @ApiOperation(value = "查询供应商列表（分页）", notes = "查询供应商列表（按创建时间倒序，支持分页）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status", value = "供应商状态：0-合作终止，1-正常合作", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageNo", value = "页码（默认1）", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数（默认10）", paramType = "query", dataType = "Integer")
    })
    @GetMapping("/list")
    public Result<Page<SupplierInfoVO>> list(
            Integer status,
            @RequestParam(defaultValue = "1") Integer pageNo,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        // 构建分页对象
        Page<SupplierInfoDTO> page = new Page<>(pageNo, pageSize);

        // 构建查询条件
        Wrapper<SupplierInfoDTO> wrapper = new EntityWrapper<>();
        if (status != null) {
            wrapper.eq("status", status);
        }
        wrapper.orderBy("create_time", false);

        // 执行分页查询
        Page<SupplierInfoDTO> resultPage = supplierInfoService.selectPage(page, wrapper);

        // DTO转VO处理
        List<SupplierInfoVO> voList = resultPage.getRecords().stream().map(dto -> {
            SupplierInfoVO vo = new SupplierInfoVO();
            BeanUtils.copyProperties(dto, vo);
            return vo;
        }).collect(Collectors.toList());

        // 封装分页结果
        Page<SupplierInfoVO> voPage = new Page<>();
        BeanUtils.copyProperties(resultPage, voPage);
        voPage.setRecords(voList);

        return new Result<>(voPage);
    }

    @ApiOperation(value = "查询供应商详情", notes = "根据ID查询供应商详情")
    @ApiImplicitParam(name = "id", value = "供应商ID", required = true, paramType = "path", dataType = "Long")
    @GetMapping("/get/{id}")
    public Result<SupplierInfoVO> get(@PathVariable Long id) {
        if (id == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        SupplierInfoDTO dto = supplierInfoService.selectById(id);
        if (dto == null) {
            return new Result<>(CodeEnum.FAIL_100010);
        }

        SupplierInfoVO vo = new SupplierInfoVO();
        BeanUtils.copyProperties(dto, vo);
        return new Result<>(vo);
    }

    @ApiOperation(value = "更新供应商", notes = "根据ID更新供应商信息（返回更新后完整数据）")
    @ApiImplicitParam(name = "id", value = "供应商ID", required = true, paramType = "path", dataType = "Long")
    @PutMapping("/update/{id}")
    public Result<SupplierInfoVO> update(
            @PathVariable Long id,
            @RequestBody SupplierInfoSaveBO saveBO) {

        // 校验记录是否存在
        SupplierInfoDTO existingDto = supplierInfoService.selectById(id);
        if (existingDto == null) {
            return new Result<>(CodeEnum.FAIL_100010);
        }

        SupplierInfoDTO updateDto = new SupplierInfoDTO();
        BeanUtils.copyProperties(saveBO, updateDto);
        updateDto.setId(id);
        updateDto.setRevision(existingDto.getRevision());

        boolean success = supplierInfoService.updateById(updateDto);
        if (success) {
            SupplierInfoDTO updatedDto = supplierInfoService.selectById(id);
            SupplierInfoVO vo = new SupplierInfoVO();
            BeanUtils.copyProperties(updatedDto, vo);
            return new Result<>(vo);
        }
        return new Result<>(CodeEnum.FAIL_100008);
    }

    @ApiOperation(value = "删除供应商", notes = "删除供应商信息")
    @ApiImplicitParam(name = "id", value = "供应商ID", required = true, paramType = "path", dataType = "Long")
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        boolean success = supplierInfoService.deleteById(id);
        return success ? new Result<>() : new Result<>(CodeEnum.FAIL_100009);
    }

    @ApiOperation(value = "切换供应商状态", notes = "根据ID切换供应商状态（返回更新后数据）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "供应商ID", required = true, paramType = "path", dataType = "Long"),
            @ApiImplicitParam(name = "status", value = "状态：0-合作终止，1-正常合作", required = true, paramType = "query", dataType = "Integer")
    })
    @PutMapping("/changestatus/{id}")
    public Result<SupplierInfoVO> changeStatus(
            @PathVariable Long id,
            @RequestParam Integer status) {

        // 业务校验
        if (status != 0 && status != 1) {
            return new Result<SupplierInfoVO>(CodeEnum.FAIL_100002.getCode(), "状态值只能是0或1");
        }

        SupplierInfoDTO dto = supplierInfoService.selectById(id);
        if (dto == null) {
            return new Result<>(CodeEnum.FAIL_100010);
        }

        dto.setStatus(status);
        boolean success = supplierInfoService.updateById(dto);
        if (success) {
            SupplierInfoDTO updatedDto = supplierInfoService.selectById(id);
            SupplierInfoVO vo = new SupplierInfoVO();
            BeanUtils.copyProperties(updatedDto, vo);
            return new Result<>(vo);
        }
        return new Result<>(CodeEnum.FAIL_100008);
    }

    @ApiOperation(value = "按名称模糊查询供应商（分页）", notes = "根据供应商名称模糊查询匹配结果（按创建时间倒序，支持分页）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "supplierName", value = "供应商名称（模糊匹配）", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "pageNo", value = "页码（默认1）", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数（默认10）", paramType = "query", dataType = "Integer")
    })
    @GetMapping("/searchByName")
    public Result<Page<SupplierInfoVO>> searchByName(
            String supplierName,
            @RequestParam(defaultValue = "1") Integer pageNo,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        // 构建分页对象
        Page<SupplierInfoDTO> page = new Page<>(pageNo, pageSize);

        // 构建查询条件
        Wrapper<SupplierInfoDTO> wrapper = new EntityWrapper<>();
        if (StrUtils.isNotEmpty(supplierName)) {
            wrapper.like("supplier_name", supplierName);
        }
        wrapper.orderBy("create_time", false);

        // 执行分页查询
        Page<SupplierInfoDTO> resultPage = supplierInfoService.selectPage(page, wrapper);

        // DTO转VO处理
        List<SupplierInfoVO> voList = resultPage.getRecords().stream().map(dto -> {
            SupplierInfoVO vo = new SupplierInfoVO();
            BeanUtils.copyProperties(dto, vo);
            return vo;
        }).collect(Collectors.toList());

        // 封装分页结果
        Page<SupplierInfoVO> voPage = new Page<>();
        BeanUtils.copyProperties(resultPage, voPage);
        voPage.setRecords(voList);

        return new Result<>(voPage);
    }
}